package cn.wawi.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * 文件上传工具类
 * @author 龚亮
 */
public class FtpUtil {

	public static String host;
	public static String port;
	public static String username;
	public static String password;
	static {
		ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
		host = bundle.getString("ftp.host");
		port = bundle.getString("ftp.port");
		username = bundle.getString("ftp.username");
		password = bundle.getString("ftp.password");
	}

	public static void main(String[] args) throws Exception {
		InputStream in = new FileInputStream(new File("d:/test.txt"));
		System.out.println(deleteFile("2015/04/17/9c2797c5-5e29-4c09-a164-9d9652b6c0a5.jpg"));
		System.out.println(uploadFile(in, "jpg"));
		System.out.println(downFile("2015/04/17/", "9ab6fa3a-abdf-4cce-8ebf-29d3ce3d335e.txt", "d:/"));
	}

	/**
	 * Description: 向FTP服务器上传文件
	 * @param extName 后缀名
	 * @param input  输入流
	 * @return 返回文件路径
	 */
	public static String uploadFile(InputStream input, String extName) {
		FTPClient ftp = new FTPClient();
		String path = "";
		try {
			ftp.connect(host, Integer.valueOf(port));// 连接FTP服务器
			ftp.setDataTimeout(5000);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			int reply;
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) { 
		            ftp.disconnect(); 
		            System.out.println("登陆失败!");
		    } 
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
			String folder = df.format(new Date());
			String[] s = folder.split("-");
			String year = s[0];// 年文件夹
			String month = s[1];// 月文件夹
			String day = s[2];// 日文件夹
			// ftpClient.makeDirectory(root);
			// 创建年月日新目录
			// year = root+"/"+year;
			ftp.makeDirectory(year);
			String folder2 = year + "/" + month;
			ftp.makeDirectory(folder2);
			folder2 = year + "/" + month + "/" + day;
			ftp.makeDirectory(folder2);
			// 设置上传目录为新目录
			// ftpClient.changeWorkingDirectory("2012/10/31/");
			ftp.setBufferSize(1024);
			ftp.setControlEncoding("GBK");//server-u默认为gbk
			// 设置文件类型（二进制）
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			String fileName = StringUtil.generateRandonFileName() + "." + extName;// 文件名
			path = folder2 + "/" + fileName;
			ftp.enterLocalPassiveMode();
			ftp.storeFile(path, input);// 保存图片到服务器
			input.close();
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return path;
	}

	/**
	 * Description: 从FTP服务器下载文件
	 * @param remotePath  FTP服务器上的相对路径
	 * @param fileName  要下载的文件名
	 * @param localPath  下载后保存到本地的路径
	 * @return
	 */
	public static boolean downFile(String remotePath, String fileName,String localPath) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, Integer.valueOf(port));
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
			ftp.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	/**
	 * 文件删除
	 * @param filePath  文件路径
	 */
	public static boolean deleteFile(String filePath){
		boolean flag=true;
		 FTPClient ftpClient = new FTPClient();
		 try {
			ftpClient.connect(host,Integer.valueOf(port));
	        ftpClient.login(username, password);
			int reply;
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) { 
				ftpClient.disconnect(); 
				flag=false;
		    } 
			flag=ftpClient.deleteFile(filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}
}
